package com.hangkong.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hangkong.model.torder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static com.alipay.api.AlipayConstants.APP_ID;
import static com.alipay.api.AlipayConstants.SIGN_TYPE;

@Controller
@RequestMapping("alipay")
public class AliPayController {
    private String priKey ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDPDtkHoQALN61oV+BKsfJbA3Ov4XKj0VuEdSPMx8qLeSuT4ikVgqpLXU08R7MQ8EJOj6XCGV4b6WEQztwCbEA/0cQ0XVQp8jLCCdso0NXNYt7yd/y7G4fc35/ShFdk0yUT/y9qRf/6T53n5kU2OOiHDjIO9HqN+rn7QnqOpHiNqmN4QHvBoBq6449EtV4MhCRNhRnZVz44WbS+n1LKT5tgVxOlktxDfdKdAf/FmYWXXJY8sQTnp31cEv8YidaLbpdpffiC4IUPl0dvklX0TLgRmAVuOSLMmdVLhyeD+2+g7JBTVv3qq3Cw8t5+KSucaZ7n9p7hO72dQkHfaD1LkVRvAgMBAAECggEAbCV/KcLnuPQtuFAdsCXdRbg51mVUcUfKGxbryeuYWNzC7Ay2FKwYsiBbVN7GIlS67TmOBCEnzEBLGHJS61kK/cpcRlVwvi/oXvyy4VCiOxInDFGrSTcJ8U1Dtrq0ws6dkSI567IADwdCnHrjL3ztxoydjL4YvMt2FEwWoyY4aRTiwW9H3Wy8LjExwr5Xdc7s3TBG5HjFA+DxpqZmW0Z2lyEyjCRlfZsxn2Hu+pqCq6HYcSJBnkp9YOkXt5KM1dD0FUCVkH4kl3zAydQo50Rvy0GLpd2DNFNHKyEcTuBiHPxDfHPfXoq5TYHf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BIk0aLGEAWG9yNGlQJAUBYfY5z/9Lo8/q+VpA5CTZ3MSMrDAdDFVdeC+GhHD3daqvXyuIXtCheoaU5edpEa9EkRm4lp1jaciii3T/cYK0I6a6mHMx8AzkusgCnkpRzTt7mpauZMC/TEtGD4pwA/vIsFI+9SQ3iryQfuwVjBQdcOKGDpea61E22qBGAoBSaJw2QFK33dpmuaLiE+2ncKrnAgugdFpnF8EaZVcuGgQIDAQAB";
    private String appId ="2016082000292675";

    @RequestMapping("alipay")
    public void aliPya(torder torder, HttpServletResponse response) throws IOException{
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", appId, priKey, "json", "UTF-8", aliKey, "RSA2"); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
//商家的返回页面（参数return_url指定页面文件）得到支付宝返回的数据，把这些数据结合自身网站情况，进行数据处理（如：订单更新）。
        alipayRequest.setReturnUrl("http://5ad579cf.ngrok.io/front/success.html");
//        一旦交易状态发生变更（如：买家已付款，等待卖家发货），支付宝便会根据自动进行数据处理，并主动调用商户在请求时设定好通知的页面路径（参数notify_url）
        alipayRequest.setNotifyUrl("http://5ad579cf.ngrok.io/front/success.html");//在公共参数中设置回跳和通知地址
        Double price = torder.getPrice();
        String orderId =torder.getPayid();


        alipayRequest.setBizContent("{" +
//                商户订单号，64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
                "    \"out_trade_no\":\""+orderId+"\"," +
//                销售产品码，与支付宝签约的产品码名称。 注：目前仅支持FAST_INSTANT_TRADE_PAY
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
//                订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
                "    \"total_amount\":"+price+"," +
//                订单标题
                "    \"subject\":\""+orderId+"\"," +
//                订单描述
                "    \"body\":\""+orderId+"\"," +
//                公用回传参数，如果请求时传递了该参数，则返回给商户时会回传该参数。支付宝只会在异步通知时将该参数原样返回。本参数必须进行UrlEncode之后才可以发送给支付宝
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"total_amount\":"+price+"," +
//	业务扩展参数，详见业务扩展参数说明
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2016082000292675\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=" + "UTF-8");
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
}
